package com.haima.ziliao.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.haima.common.annotation.RepeatSubmit;
import com.haima.common.utils.DateUtils;
import com.haima.common.utils.SecurityUtils;
import com.haima.utils.OrderGen;
import com.haima.utils.WeChatConstant;
import com.haima.utils.WxPayTool;
import com.haima.ziliao.domain.*;
import com.haima.ziliao.service.*;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;
import com.haima.common.annotation.Log;
import com.haima.common.core.controller.BaseController;
import com.haima.common.core.domain.AjaxResult;
import com.haima.common.enums.BusinessType;
import com.haima.common.utils.poi.ExcelUtil;
import com.haima.common.core.page.TableDataInfo;

/**
 * 订单管理Controller
 * 
 * @author hima
 * @date 2024-10-21
 */
@RestController
@RequestMapping("/ziliao/orders")
public class POrdersController extends BaseController
{
    @Autowired
    private IPOrdersService pOrdersService;
    @Autowired
    private IPVipconfigService vipconfigService;
    @Autowired
    private IPDayinOrderService dayinOrderService;
    @Autowired
    private IPDuwuService duwuService;
    @Autowired
    private IPUservipService uservipService;
    @Autowired
    private IPMyduwuService myduwuService;

    /**
     * 查询订单管理列表
     */
    @GetMapping("/list")
    public TableDataInfo list(POrders pOrders)
    {
        startPage();
        List<POrders> list = pOrdersService.selectPOrdersList(pOrders);
        return getDataTable(list);
    }

    @GetMapping("/listByUser")
    public TableDataInfo listByUser(POrders pOrders)
    {
        pOrders.setUid(SecurityUtils.getUserId());
        startPage();
        List<POrders> list = pOrdersService.selectPOrdersList(pOrders);
        return getDataTable(list);
    }
    @GetMapping("/getDetail")
    public AjaxResult getDetail(POrders pOrders)
    {
        POrders orders = pOrdersService.selectPOrdersById(pOrders.getId());

        String type = orders.getOrderType();

        if("vip".equals(type)){
           PVipconfig vc = vipconfigService.selectPVipconfigById(orders.getBid());
            orders.setVipconfig(vc);
        } else if("dayin".equals(type)){
            PDayinOrder dayinOrder = dayinOrderService.selectPDayinOrderById(orders.getBid());
            orders.setDayinOrder(dayinOrder);
        }
        return AjaxResult.success(orders);
    }
    @GetMapping("/getNum")
    public AjaxResult getNum()
    {
        Map<String,Object> map = new HashMap<>();

        Long dds = pOrdersService.count(new QueryWrapper<POrders>().eq("uid",SecurityUtils.getUserId()));

        map.put("orderNum",dds);

        return AjaxResult.success(map);
    }

    /**
     * 导出订单管理列表
     */
    @PreAuthorize("@ss.hasPermi('ziliao:orders:export')")
    @Log(title = "订单管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, POrders pOrders)
    {
        List<POrders> list = pOrdersService.selectPOrdersList(pOrders);
        ExcelUtil<POrders> util = new ExcelUtil<POrders>(POrders.class);
        util.exportExcel(response, list, "订单管理数据");
    }

    /**
     * 获取订单管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('ziliao:orders:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(pOrdersService.selectPOrdersById(id));
    }

    /**
     * 新增订单管理
     */
    @PreAuthorize("@ss.hasPermi('ziliao:orders:add')")
    @Log(title = "订单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody POrders pOrders)
    {
        return toAjax(pOrdersService.insertPOrders(pOrders));
    }

    @PostMapping("/openvip")
    @RepeatSubmit
    public AjaxResult openVip(@RequestParam("vid") Long vid)
    {
        PVipconfig config = vipconfigService.selectPVipconfigById(vid);
        Long uid = SecurityUtils.getUserId();
        String openid = SecurityUtils.getUsername();


        POrders order = new POrders();
        order.setUid(uid);
        order.setOrderType("vip");
        order.setJine(config.getXianjia().toString());
        order.setName(config.getName());
        order.setOrderNum(OrderGen.generateOrderNumber());
        order.setAddTime(DateUtils.getNowDate());
        order.setBid(vid);
        order.setStatus("1");
        try {
            pOrdersService.insertPOrders(order);

            PrepayRequest pre = getPrepayRequest(config, order, openid);
            PrepayWithRequestPaymentResponse response = WxPayTool.prepayWithRequestPayment(pre);
            System.out.println("============================================预支付信息=====================================================");
            System.out.println(JSON.toJSON(response));
            return AjaxResult.success(response);
        }catch (Exception e) {
            return AjaxResult.error("获取支付信息失败");
        }
    }

    @PostMapping("/freeDuWuOrders")
    @RepeatSubmit
    public AjaxResult freeDuWuOrders(@RequestParam("id") Long id){
        PDuwu dw = duwuService.selectPDuwuById(id);
        Long uid = SecurityUtils.getUserId();
        PUservip vip = uservipService.getOne(new QueryWrapper<PUservip>().eq("uid",uid));

        POrders order = new POrders();
        order.setUid(uid);
        order.setOrderType("duwu");
        order.setJine("0.00");
        order.setName("读物"+dw.getTitle());
        order.setOrderNum(OrderGen.generateOrderNumber());
        order.setAddTime(DateUtils.getNowDate());
        order.setBid(id);
        order.setStatus("2");
        order.setShifu("0.00");
        order.setWxNum("--");
        order.setPayTime(DateUtils.getNowDate().toString());

        if("1".equals(dw.getFree())){//完全免费
            pOrdersService.insertPOrders(order);
            //处理VIP信息
            PMyduwu pmd = new PMyduwu();
            pmd.setUid(uid);
            pmd.setBuytime(order.getAddTime());
            pmd.setDid(order.getBid());
            pmd.setTitle(dw.getTitle());
            pmd.setDownloadurl(dw.getPath());
            myduwuService.insertPMyduwu(pmd);
            return AjaxResult.success();
        }else if("1".equals(dw.getNeedvip())&&vip!=null&&"1".equals(vip.getStatus())){//会员免费
            pOrdersService.insertPOrders(order);
            PMyduwu pmd = new PMyduwu();
            pmd.setUid(uid);
            pmd.setBuytime(order.getAddTime());
            pmd.setDid(order.getBid());
            pmd.setTitle(dw.getTitle());
            pmd.setDownloadurl(dw.getPath());
            myduwuService.insertPMyduwu(pmd);
            return AjaxResult.success();
        }else {//数据错误
            return AjaxResult.error("文件需要付费或会员已过期");
//            if("2".equals(dw.getFree())||"2".equals(dw.getNeedvip())){//文件不免费
//
//            }
//            if("1".equals(dw.getNeedvip())&&"2".equals(vip.getStatus())){//会员已过期
//
//            }
        }

    }

    @PostMapping("/buyduwu")
    @RepeatSubmit
    public AjaxResult buyduwu(@RequestParam("id") Long id)
    {

        PDuwu dw = duwuService.selectPDuwuById(id);

        Long uid = SecurityUtils.getUserId();
        String openid = SecurityUtils.getUsername();

        PUservip vip = uservipService.getOne(new QueryWrapper<PUservip>().eq("uid",uid));

        BigDecimal jine = new BigDecimal("0");

        if(vip!=null&&"1".equals(vip.getStatus())){
            jine = jine.add(dw.getHuiyuanjia());
        }else{
            jine = jine.add(dw.getXianjia());
        }


        POrders order = new POrders();
        order.setUid(uid);
        order.setOrderType("duwu");
        order.setJine(jine.toString());
        order.setName("读物"+dw.getTitle());
        order.setOrderNum(OrderGen.generateOrderNumber());
        order.setAddTime(DateUtils.getNowDate());
        order.setBid(id);
        order.setStatus("1");
        try {
            pOrdersService.insertPOrders(order);

            PrepayRequest pre = getDwPrepayRequest(jine, order, openid);
            PrepayWithRequestPaymentResponse response = WxPayTool.prepayWithRequestPayment(pre);
            System.out.println("============================================预支付信息=====================================================");
            System.out.println(JSON.toJSON(response));
            return AjaxResult.success(response);
        }catch (Exception e) {
            return AjaxResult.error("获取支付信息失败");
        }
    }

    private static PrepayRequest getDwPrepayRequest(BigDecimal jine, POrders order, String openid){
        PrepayRequest pre = new PrepayRequest();

        BigDecimal fen = jine.multiply(new BigDecimal(100));
        Integer fenres = fen.intValue();


        Amount amount = new Amount();
        amount.setTotal(fenres);
        pre.setAmount(amount);
        pre.setDescription(order.getName());
        pre.setOutTradeNo(order.getOrderNum());
        pre.setNotifyUrl(WeChatConstant.DUWU_NOTICE_URL);
        Payer payer = new Payer();
        payer.setOpenid(openid);
        pre.setPayer(payer);
        return pre;
    }

    private static PrepayRequest getPrepayRequest(PVipconfig config, POrders order, String openid) {
        PrepayRequest pre = new PrepayRequest();

        BigDecimal fen = config.getXianjia().multiply(new BigDecimal(100));
        Integer fenres = fen.intValue();


        Amount amount = new Amount();
        amount.setTotal(fenres);
        pre.setAmount(amount);
        pre.setDescription("伴学会员VIP年卡");
        pre.setOutTradeNo(order.getOrderNum());
        pre.setNotifyUrl(WeChatConstant.VIP_NOTICE_URL);
        Payer payer = new Payer();
        payer.setOpenid(openid);
        pre.setPayer(payer);
        return pre;
    }

//    public static void main(String[] args) throws IOException {
//        BigDecimal decimal = new BigDecimal("2000.23");
//        String val = decimal.toString();
//        Integer vla1 = decimal.intValue();
//        System.out.println(vla1);
//
//    }

    /**
     * 修改订单管理
     */
    @PreAuthorize("@ss.hasPermi('ziliao:orders:edit')")
    @Log(title = "订单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody POrders pOrders)
    {
        return toAjax(pOrdersService.updatePOrders(pOrders));
    }

    /**
     * 删除订单管理
     */
    @PreAuthorize("@ss.hasPermi('ziliao:orders:remove')")
    @Log(title = "订单管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(pOrdersService.deletePOrdersByIds(ids));
    }
}
